package com.android.kotlin.util

class Resource<T> private constructor(val status: Status, val data: T?, val message: String?, val tag: String?) {

    override fun toString(): String {
        return "Resource{" +
                "status=" + status +
                ", data=" + data +
                ", message='" + message + '\''.toString() +
                '}'.toString()
    }


    fun handle(callback: OnHandleCallback<T>) {
        if (status == Status.SUCCESS) {
            callback.onSuccess(data)
        } else if (status == Status.ERROR) {
            callback.onError()

        } else if (status == Status.EMPTY) {
            callback.onEmpiy()
        }
        if (status != Status.LOADING) {
            callback.onCompleted()
        }
    }


    interface OnHandleCallback<T> {
        fun onSuccess(data: T?)
        fun onEmpiy()
        fun onError()
        fun onCompleted()
    }

    companion object {
        fun <T> success(data: T, tag: String?=""): Resource<T> {
            return Resource(Status.SUCCESS, data, null, tag)
        }

        fun <T> error(msg: String?="", data: T?, tag: String?=""): Resource<T> {
            return Resource(Status.ERROR, data, msg, tag)
        }

        fun <T> loading(data: T?, tag: String?=""): Resource<T> {
            return Resource(Status.LOADING, data, null, tag)
        }

        fun <T> empty(tag: String?=""): Resource<T> {
            return Resource(Status.EMPTY, null, null, tag)
        }

        fun <T> reload(data: T?, tag: String?=""): Resource<T> {
            return Resource(Status.RELOAD, data, null, tag)
        }
    }
}
